﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace BUS_QLNS.Tools
{
    public class Email
    {
        public static string Send_Email(string SendTo, string Subject, string Body)
        {
            try
            {
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                bool result = regex.IsMatch(SendTo);
                if (result == false)
                {
                    return "Địa chỉ email không hợp lệ.";
                }
                else
                {
                    MailMessage mailMessage = new MailMessage();
                    String Host = "";
                    int Port = 0;
                    if (SendTo.Contains("@gmail"))
                    {
                        Host = "smtp.gmail.com";
                        Port = 587;
                    }
                    else if (SendTo.Contains("@yahoo"))
                    {
                        Host = "smtp.mail.yahoo.com";
                        Port = 465;
                    }
                    else if (SendTo.Contains("@ntlworld"))
                    {
                        Host = "smtp.ntlworld.com";
                        Port = 465;
                    }
                    else if (SendTo.Contains("@hotmail"))
                    {
                        Host = "smtp.live.com";
                        Port = 587;
                    }
                    SmtpClient mailClient = new SmtpClient(Host, Port);
                    mailClient.Timeout = 15000;
                    mailClient.Credentials = new NetworkCredential("ecmoney07@gmail.com", "ecmoney07");
                    mailClient.EnableSsl = true;
                    mailMessage.IsBodyHtml = true;
                    mailMessage.From = new MailAddress("ecmoney07@gmail.com");
                    mailMessage.Subject = Subject;
                    mailMessage.Body = Body;
                    mailMessage.To.Add(SendTo);
                    try
                    {
                        mailClient.Send(mailMessage);
                        return "Send mail success";
                    }
                    catch (Exception ex)
                    {
                        return ("Send mail fail, " + ex.Message).ToString();
                    }
                }
            }
            catch
            {
                return "";
            }
        }
    }
}
